Page({
  data: {
    avatarUrl: '',
    nickname: '',
    mobile: '',
    gender: '男'
  },
  onLoad() {
    // 可以按需从上个页面传入或从本地存储读取初始值
    const user = wx.getStorageSync('user_profile') || {};
    this.setData({
      avatarUrl: user.avatarUrl || '',
      nickname: user.nickname || '笑看人生',
      mobile: user.mobile || '1433560078',
      gender: user.gender || '男'
    });
  },

  onChangeAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const filePath = (res.tempFiles && res.tempFiles[0] && res.tempFiles[0].tempFilePath) || '';
        if (filePath) {
          // 本地先行预览
          this.setData({ avatarUrl: filePath });
          // 预留上传接口
          this.uploadAvatar(filePath)
            .then((remoteUrl) => {
              if (remoteUrl) {
                this.setData({ avatarUrl: remoteUrl });
              }
            })
            .catch(() => {
              // 忽略错误，保持本地预览
            });
        }
      }
    });
  },

  onNicknameInput(e) {
    this.setData({ nickname: e.detail.value });
  },

  onMobileInput(e) {
    this.setData({ mobile: e.detail.value });
  },

  onGenderChange(e) {
    this.setData({ gender: e.detail.value });
  },

  onCancel() {
    wx.navigateBack();
  },

  onSubmit() {
    // 这里可按需发起请求提交到后端
    const payload = {
      avatarUrl: this.data.avatarUrl,
      nickname: this.data.nickname,
      mobile: this.data.mobile,
      gender: this.data.gender
    };
    // 存个本地，示意
    wx.setStorageSync('user_profile', payload);

    console.log(payload);
    wx.showToast({ title: '已提交', icon: 'success', duration: 800 });
    setTimeout(() => {
      wx.navigateBack();
    }, 1000);
  },

  // 预留：上传头像到服务器，返回远程可访问URL
  uploadAvatar(localPath) {
    return new Promise((resolve, reject) => {
      // 如果后续需要改为真实上传，只需替换下面的逻辑
      // 示例：
      // wx.uploadFile({
      //   url: 'https://your.domain.com/api/upload',
      //   name: 'file',
      //   filePath: localPath,
      //   formData: {},
      //   success: (res) => {
      //     const data = JSON.parse(res.data || '{}');
      //     resolve(data.url);
      //   },
      //   fail: reject
      // });

      // 目前先直接resolve本地路径作为占位
      resolve(localPath);
    });
  }
});


